package com.atguigu.eduservice.service.impl;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.UserClient;
import com.atguigu.eduservice.entity.EduComment;
import com.atguigu.commonutils.ClientEntity.ClientMember;
import com.atguigu.eduservice.mapper.EduCommentMapper;
import com.atguigu.eduservice.service.EduCommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 评论 服务实现类
 * </p>
 *
 * @author huangqicai
 * @since 2023-03-30
 */
@Service
public class EduCommentServiceImpl extends ServiceImpl<EduCommentMapper, EduComment> implements EduCommentService {

    @Autowired
    private UserClient userClient;

    @Override
    public R getPageList(long current, long limit, String courseId) {
        Page<EduComment> page = new Page<>(current, limit);
        Page<EduComment> pageParam = (Page)baseMapper.selectPage(page, new QueryWrapper<EduComment>().eq("course_id", courseId));
        Map<String, Object> map = new HashMap<>();
        map.put("items", pageParam.getRecords());
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map);
    }


    /*新增评论*/
    @Override
    public R addComment(EduComment eduComment,HttpServletRequest request) {
        /*1.获取当前登录用户的信息*/
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        System.out.println("userId:"+userId);
        ClientMember parse = userClient.getLoginInfo(userId);
        if(StringUtils.isEmpty(parse)){
            return R.error().message("请先登录~");
        }
        /*2.发布评论*/
        eduComment.setMemberId(userId);
        eduComment.setAvatar(parse.getAvatar());
        eduComment.setNickname(parse.getNickname());
        System.out.println("11111");
        baseMapper.insert(eduComment);
        return R.ok();
    }

}
